package net.moonbiter.ebs.docs;

import net.moonbiter.BugException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

import org.eclipse.jdt.internal.compiler.ast.ThisReference;

import net.moonbiter.ebs.descriptors.Descriptor;
import net.moonbiter.ebs.descriptors.PropertiesDescriptor;
import net.moonbiter.ebs.descriptors.InstantiatorDescriptor;

public aspect DescriptorWriting {
	
	declare parents : PropertiesDescriptor implements DescriptorWriter;
	declare parents : InstantiatorDescriptor implements DescriptorWriter;
	
	private static String indent(String str, int indentation){
		BufferedReader reader = new BufferedReader(new StringReader(str));
		StringBuffer result = new StringBuffer();
		String line;
		try {
			while (null!=(line=reader.readLine())){
				for (int i=0;i<indentation;i++){
					result.append("\t");
				}
				result.append(line);
				result.append("\n");
			}
			return result.toString();
		} catch (IOException e) {
			throw new BugException("A string reader have not to throw IOExceptions");
		}
	}

	public static String getText(Descriptor<?, ?> descriptor) {		
		if (descriptor instanceof DescriptorWriter) {
			DescriptorWriter descriptorWriter = (DescriptorWriter)descriptor;
			return DescriptorWriting.indent(descriptorWriter.write(),2);
		} else {
			return "\t\tI don't know how to describe the descriptor...";
		}
	}

	public String PropertiesDescriptor.write() {
		StringBuffer buf = new StringBuffer();
		
		for (String propName : getSetters().keySet()) {
			buf.append(propName + ": ");
			if (getSpecificDescriptors().containsKey(propName)){
				buf.append(getText(getSpecificDescriptors().get(propName)));			
			} else {
				buf.append("no specific descriptor");
			}
			buf.append("\n");
		}
		return buf.toString();
	}
	
	public String InstantiatorDescriptor.write() {
		StringBuffer buf = new StringBuffer();
		
		for (int i=0;i<getNbOfConstructorParams();i++) {
			buf.append(""+ i + ": ");
			if (getSpecificDescriptors().containsKey(i)){
				buf.append(getText(getSpecificDescriptors().get(i)));				
			} else {
				buf.append("no specific descriptor");
			}
			buf.append("\n");
		}
		return buf.toString();
	}
}
